<template>
  <div class="search-container">
    <!-- 搜索栏事件监听 -->
    <form action="/" class="form">
      <van-search
        v-model="value"
        show-action
        class="search"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @focus="isShowResult = false"
      >
        <!-- search搜索框 -->
        <template #action>
          <div @click="onSearch(value)">搜索</div>
        </template></van-search
      >
      <!-- search事件 -->
    </form>
    <!-- <search-result v-if="isShowResult"></search-result>
    <search-suggestion v-if="value && !isShowResult"></search-suggestion>
    <search-history v-if="!isShowResult && !value"></search-history> -->
    <!-- 3个互斥 -->
    <div class="content">
      <search-result v-if="isShowResult" :input="value"></search-result>
      <search-suggestion
        v-else-if="value"
        :searchText="value"
        @search="onSearch"
      ></search-suggestion>
      <!-- 子组件的传值 -->
      <search-history
        v-else
        :history="history"
        @search="onSearch"
        @deleteAllHistory="history = []"
      ></search-history>
    </div>
  </div>
</template>

<script>
import SearchHistory from "./components/search-history.vue";
import SearchResult from "./components/search-result.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
import { setLocalStorage, getLocalStorage } from "@/utlis/localstorage";
export default {
  name: "search-container",
  data() {
    return {
      value: "",
      isShowResult: false,
      history: getLocalStorage("search-history") || [],
    };
  },
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion,
  },

  created() {},

  methods: {
    onSearch(val) {
      // 数据并不重复，最新的在前面
      let index = this.history.indexOf(val);
      if (index !== -1) {
        this.history.splice(index, 1);
      }
      this.history.unshift(val);
      console.log(this.history);

      this.value = val;
      this.isShowResult = true;
    },
  },
  // 将历史记录存放到本地存储中
  watch: {
    history(val) {
      setLocalStorage("search-history", val);
    },
  },
};
</script>

<style scoped lang='less'>
.search-container {
  .form {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
  }
  .search {
    background-color: #1989fa;
    .van-search__action {
      color: #fff;
    }
    .van-search__action:active {
      background-color: #1989fa;
    }
  }
  .content {
    padding-top: 108px;
  }
}
</style>